package br.com.beautycenter.view;

import br.com.beautycenter.DAO.PersisteCliente;
import br.com.beautycenter.DAO.PersistePrestacao;
import br.com.beautycenter.Funcionalidades.Swing;
import br.com.beautycenter.Funcionalidades.Validacoes;
import br.com.beautycenter.ModelosTabela.TableModelConfirmarVenda;
import br.com.beautycenter.bean.Cliente;
import br.com.beautycenter.bean.Prestacao;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JOptionPane;

public class ConfirmarPagamento extends javax.swing.JFrame {

    PersistePrestacao persistePrestacao = new PersistePrestacao();
    PersisteCliente persisteCliente = new PersisteCliente();
    
    Cliente cliente;
    List<Prestacao> listaPrestacaos = new ArrayList<Prestacao>();
    List<Cliente> listaClientes = new ArrayList<Cliente>();
    
    final TableModelConfirmarVenda modelo = new TableModelConfirmarVenda(this, listaPrestacaos);
    
    public void confirmar(){
        if(jCCliente.getSelectedIndex() > 0){
            cliente = listaClientes.get(jCCliente.getSelectedIndex()-1);
            modelo.setCliente(cliente);
            
            preencherTabela();
            
        }else{
            JOptionPane.showMessageDialog(null, "Selecione um cliente...");
        }
    }
    
    public void preencherTabela(){
        listaPrestacaos.clear();
        listaPrestacaos = persistePrestacao.retornarPrestacoesAtivasPorCliente(cliente);
        for(Prestacao item: listaPrestacaos){
            item.setSelecionado(false);
        }
        
        modelo.clear(); //limpar a tabela
        modelo.addListaPrestacaoes(listaPrestacaos);
    }
    
    public void preencherComboCliente(){
        jCCliente.removeAllItems();
        jCCliente.addItem("Selecione um cliente");
        
        //adiciona apenas clientes com vendas pendentes, seja ele ativo ou não
        List<Prestacao> temp = persistePrestacao.retornarPrestacoesAtivas();
        listaClientes.clear();
        
        
        boolean add; //verifica se tem que adicionar o cliente na lista ou não
        
        //for que percorre todas as prestações ativas
        for(int i=0; i<temp.size(); i++){
            add = true;
            //for com os clientes existentes na lista de clientes
            for(Cliente item: listaClientes){
                //se o clientes da prestação já está na lista de clientes, então não precisa ser inserido novamente
                if(temp.get(i).getVenda().getCliente().getIdPessoa() == item.getIdPessoa()) {
                    add = false;
                    break;
                }
            }
            
            //se não consta na lista, então adiciona
            if(add){
                listaClientes.add(temp.get(i).getVenda().getCliente());
            }
        }
        
        //preenche o combo com os clientes escolhidos
        for(Cliente item:listaClientes){
            jCCliente.addItem(item.getNome());
        }
    }
    
    public void preencherValores(){
        double somatorio = modelo.somatorioSelecionado();
        
        //se o total selecionado for 0, então desativa os campos sobre os valores
        if((int)somatorio == 0){
            Swing.desativarCampos(jPValores.getComponents());
            txtValorRecebido.setText("");
            txtValorPrestacao.setText("");
        }else{
            Swing.ativarCampos(jPValores.getComponents());
            txtValorRecebido.requestFocus();
            txtValorRecebido.setText(Validacoes.formatoMoeda.format(somatorio));
            txtValorRecebido.select(0, txtValorRecebido.getText().trim().length());

            txtValorPrestacao.setText(Validacoes.formatoMoeda.format(somatorio));
        }
    }
        
    public void limparTela(){
        jCCliente.setSelectedIndex(0); //volta o combro pro "selecione um cliente..."
        modelo.clear(); //limpar a tabela
        Swing.zerarCampos(jPValores.getComponents());
        Swing.desativarCampos(jPValores.getComponents());
    }
    
    public void salvar(){
        
        Double valorRecebido = Validacoes.validarCampoMoeda(txtValorRecebido.getText().trim());
        Double valorPrestacao = Validacoes.validarCampoMoeda(txtValorPrestacao.getText().trim());
        
        if(valorRecebido == null){
            JOptionPane.showMessageDialog(null, "Valor informado é inválido.");
        }else if(valorRecebido.intValue() == 0){
            JOptionPane.showMessageDialog(null, "Valor recebido deve ser maior que 0.");
        }else if(valorRecebido.compareTo(valorPrestacao) > 0){
            JOptionPane.showMessageDialog(null, "Valor recebido dever ser menor ou igual o valor total selecionado.");
        }else if(valorRecebido.compareTo(valorPrestacao) < 0){
            modelo.redefinirPrestacoes(valorRecebido);
            limparTela();
        }else{
            modelo.quitarPrestacoes();
            limparTela();
        }
        
    }
    
    public void selecionar(){
        int coluna = jTablePrestacoes.getSelectedColumn();
        
        if(coluna == 0){
            preencherValores();//preenche os valores com as linhas selecionadas
        }
    }
    
    public void sair(){
        dispose();
    }
        
    public void inicializarTela(){
        jTablePrestacoes.setModel(modelo);
        preencherComboCliente();
        limparTela();
    }
    

    public ConfirmarPagamento() {
        initComponents();
        inicializarTela();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jPDados = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jCCliente = new javax.swing.JComboBox();
        btnConfirmar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTablePrestacoes = new javax.swing.JTable();
        jPValores = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        txtValorRecebido = new javax.swing.JTextField();
        txtValorPrestacao = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jPainelBotoes = new javax.swing.JPanel();
        btnSalvar = new javax.swing.JButton();
        btnSair = new javax.swing.JButton();

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 100, Short.MAX_VALUE)
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Recebimento");

        jPDados.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Informe o cliente", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION));

        jLabel1.setText("Cliente");

        btnConfirmar.setText("Confirmar");
        btnConfirmar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnConfirmarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPDadosLayout = new javax.swing.GroupLayout(jPDados);
        jPDados.setLayout(jPDadosLayout);
        jPDadosLayout.setHorizontalGroup(
            jPDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPDadosLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jCCliente, javax.swing.GroupLayout.PREFERRED_SIZE, 290, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(btnConfirmar)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPDadosLayout.setVerticalGroup(
            jPDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPDadosLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPDadosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jCCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnConfirmar))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jTablePrestacoes.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "*", "Data", "Valor Prestação"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Boolean.class, java.lang.Object.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTablePrestacoes.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTablePrestacoesMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTablePrestacoes);
        if (jTablePrestacoes.getColumnModel().getColumnCount() > 0) {
            jTablePrestacoes.getColumnModel().getColumn(0).setMinWidth(30);
            jTablePrestacoes.getColumnModel().getColumn(0).setPreferredWidth(30);
            jTablePrestacoes.getColumnModel().getColumn(0).setMaxWidth(30);
        }

        jPValores.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Informe o valor recebido", javax.swing.border.TitledBorder.CENTER, javax.swing.border.TitledBorder.DEFAULT_POSITION));

        jLabel2.setText("Valor Recebido");

        txtValorPrestacao.setEditable(false);

        jLabel3.setText("Total Selecionado");

        javax.swing.GroupLayout jPValoresLayout = new javax.swing.GroupLayout(jPValores);
        jPValores.setLayout(jPValoresLayout);
        jPValoresLayout.setHorizontalGroup(
            jPValoresLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPValoresLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtValorRecebido, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(txtValorPrestacao, javax.swing.GroupLayout.PREFERRED_SIZE, 98, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPValoresLayout.setVerticalGroup(
            jPValoresLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPValoresLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPValoresLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtValorRecebido, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(txtValorPrestacao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPainelBotoes.setPreferredSize(new java.awt.Dimension(800, 45));

        btnSalvar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/beautycenter/img/Salvar.png"))); // NOI18N
        btnSalvar.setToolTipText("SALVAR");
        btnSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalvarActionPerformed(evt);
            }
        });

        btnSair.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/beautycenter/img/Sair.png"))); // NOI18N
        btnSair.setToolTipText("SAIR");
        btnSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSairActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPainelBotoesLayout = new javax.swing.GroupLayout(jPainelBotoes);
        jPainelBotoes.setLayout(jPainelBotoesLayout);
        jPainelBotoesLayout.setHorizontalGroup(
            jPainelBotoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPainelBotoesLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btnSalvar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnSair)
                .addGap(151, 151, 151))
        );
        jPainelBotoesLayout.setVerticalGroup(
            jPainelBotoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPainelBotoesLayout.createSequentialGroup()
                .addGroup(jPainelBotoesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnSalvar)
                    .addComponent(btnSair))
                .addGap(0, 4, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPValores, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
            .addComponent(jPainelBotoes, javax.swing.GroupLayout.DEFAULT_SIZE, 448, Short.MAX_VALUE)
            .addComponent(jPDados, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPainelBotoes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPDados, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 299, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPValores, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalvarActionPerformed
        salvar();
    }//GEN-LAST:event_btnSalvarActionPerformed

    private void btnSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSairActionPerformed
        sair();
    }//GEN-LAST:event_btnSairActionPerformed

    private void jTablePrestacoesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTablePrestacoesMouseClicked
        selecionar();
    }//GEN-LAST:event_jTablePrestacoesMouseClicked

    private void btnConfirmarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnConfirmarActionPerformed
        confirmar();
    }//GEN-LAST:event_btnConfirmarActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnConfirmar;
    private javax.swing.JButton btnSair;
    private javax.swing.JButton btnSalvar;
    private javax.swing.JComboBox jCCliente;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPDados;
    private javax.swing.JPanel jPValores;
    private javax.swing.JPanel jPainelBotoes;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTablePrestacoes;
    private javax.swing.JTextField txtValorPrestacao;
    private javax.swing.JTextField txtValorRecebido;
    // End of variables declaration//GEN-END:variables
}